﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlowBasis.Web.Mvc;
using FlowBasis.Data;
using FlowBasisSampleSite.Domain.Entities;
using System.Net;
using FlowBasis.Json;

namespace FlowBasisSampleSite.Areas.Admin.Controllers
{

    [UserAuthorize(RequiredPermissions = new[] { FlowBasis.Security.BasicPermissions.SiteAdmin })]
    public class PermissionsController : Controller
    {
        private IDataService dataService;

        public PermissionsController(IDataService dataService)
        {
            this.dataService = dataService;
        }

        public ActionResult Index()
        {
            List<Permission> permissions = this.dataService.GetAll<Permission>()
                .OrderBy(p => p.Name)
                .ToList();

            ViewBag.Permissions = permissions;

            return View();
        }

        public ActionResult Info(int id)
        {
            Permission permission = this.dataService.GetAll<Permission>().FirstOrDefault(p => p.PermissionId == id);
            if (permission == null)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);
            }

            ViewBag.Permission = permission;

            return View();
        }


        [PostRpc]
        public ActionResult GetPermissionList(
            PermissionQuery query,
            int? offset,
            int? maxResults)
        {
            if (query == null)
                query = new PermissionQuery();

            IQueryable<Permission> permissionQuery = this.dataService.GetAll<Permission>();

            if (!String.IsNullOrWhiteSpace(query.MatchText))
            {
                string matchText = query.MatchText.Trim();

                permissionQuery = permissionQuery.Where(ua => ua.Name.Contains(matchText));
            }

            permissionQuery = permissionQuery.OrderBy(ua => ua.Name);

            var resultSet = permissionQuery.ToJObjectResultSet(
                offset,
                maxResults,
                (permission) =>
                {
                    dynamic permissionData = new JObject();
                    permissionData.id = permission.PermissionId;
                    permissionData.name = permission.Name;

                    return permissionData;
                });

            return new PostRpcResult(resultSet);
        }


        public class PermissionQuery
        {
            public string MatchText { get; set; }
        }
    }
}
